package com.link4a.doms.service;

import java.io.IOException;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;

import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 * @author brown
 */
public final class FreemarkerService {

	private Configuration configuration;

	public String mergeTemplateIntoString(String template) throws IOException, TemplateException {
		return mergeTemplateIntoString(template, null, null);
	}

	public String mergeTemplateIntoString(String template, Locale locale) throws IOException, TemplateException {
		return mergeTemplateIntoString(template, null, locale);
	}

	public String mergeTemplateIntoString(String template, Map<String, Object> model) throws IOException, TemplateException {
		return mergeTemplateIntoString(template, model, null);
	}

	public String mergeTemplateIntoString(String template, Map<String, Object> model, Locale locale) throws IOException, TemplateException {
		if (model == null) {
			model = Collections.emptyMap();
		}
		if (locale == null) {
			locale = Locale.getDefault();
		}
		if (!template.endsWith(".ftl")) {
			template += ".ftl";
		}
		return FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(template, locale), model);
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}
}
